import {Command} from '../constant';
import Taro from '@tarojs/taro';
import {Dispatch} from 'typings';
import {IAllReducerProps} from '../types';
import {getReducerData} from '@/redux/store';
import {extraPathsValue} from '@/redux/util';
import api from 'api';
import moment from 'dayjs';
import {Const} from 'config';
import {CustomerSignRecordInitInfoResponse} from 'api/CustomerSignRecordController';

export default (dispatch: Dispatch) => {
  let action = {
    commonChange(...param: any) {
      dispatch({
        type: Command.commonChange,
        payload: extraPathsValue(...arguments),
      });
    },
    async page() {
      let uniqueID = Taro.getStorageSync('uniqueID');
      const res = await Promise.all([
        api.systemPointsConfigController.queryPointsConfig(), //查询积分设置-最新
        api.pointsMallController.getCateList({deviceNum: uniqueID}), //查询积分商品分类
        api.pointsMallController.findCustomerInfo(), //获取用户积分信息
        api.systemPointsConfigController.query(), //查询积分设置-原有
        api.customerSignRecordController.getCustomerInfo(), //查询用户信息
        api.customerSignRecordController.getListByThisMonth(), //列表查询当月用户签到记录
      ]);
      let titleList = [];
      if (res[1].pointsGoodsCateVOList.length > 0) {
        res[1].pointsGoodsCateVOList.map((item) => {
          let obj = {title: ''};
          obj.title = item.cateName;
          titleList.push(obj);
        });
      }

      let continuousDays = res[4].customerVO.signContinuousDays; //签到天数
      let signPoints = res[0].signPoints; //签到获取积分
      // let continueSignDay = res[0].monthFirstDaySignPoints; //每月第一天签到获取积分
      let signFlag = res[4].signFlag; //今日是否签到标志
      let daysNumArr = []; //展示7天签到记录
      let cont = 0;

      if (continuousDays == 7 && !signFlag) {
        //连续签到日期已达7天，今天未签。一个连续签到周期已经结束，按第一天未签到效果展示
        cont = 0;
      } else if (signFlag) {
        //今天已签
        cont = continuousDays - 1; //除去今天往前推n天
      } else {
        //今天未签
        cont = continuousDays;
      }

      //根据签到状态获取当前7天数据
      let sevenDaysAgo = new Date();
      sevenDaysAgo.setDate(sevenDaysAgo.getDate() - cont);
      for (let i = 0; i <= 6; i++) {
        let obj = {date: '', signPoints: 0, signType: false};
        const date = new Date(sevenDaysAgo);
        date.setDate(sevenDaysAgo.getDate() + i);
        obj.date = moment(date).format('YYYY-MM-DD');
        obj.signPoints = signPoints;
        if (moment(date).isBefore(new Date())) {
          //今天之前时间全部为已签到
          obj.signType = true;
        }
        if (moment(date).format('YYYY-MM-DD') == moment(new Date()).format('YYYY-MM-DD')) {
          //时间为今天赋值当天签到状态
          obj.signType = signFlag;
        }
        console.log('-------obj');
        console.log(obj);
        daysNumArr.push(obj);
      }

      dispatch({
        type: Command.init,
        payload: {
          main: {
            tabList: res[1].pointsGoodsCateVOList,
            titleList: titleList,
            selectId: res[1].pointsGoodsCateVOList.length > 0 ? res[1].pointsGoodsCateVOList[0].cateId : null,
            pageNum: 0,
            pointsAvailable: res[2] && res[2].pointsAvailable ? res[2].pointsAvailable : null,
            pointsExpireDay: res[3] && res[3].pointsExpireDay ? res[3].pointsExpireDay : null,
            pointsExpireMonth: res[3] && res[3].pointsExpireMonth ? res[3].pointsExpireMonth : null,
            continuousDays,
            signFlag,
            signRecordList: res[5].customerSignRecordVOList,
            daysNumArr,
          },
        },
      });
      if (titleList.length > 0) {
        this.findPointsMall();
      }
    },
    /**
     * 根据分类查询积分商品列表
     */
    async findPointsMall() {
      let {selectId, pageNum, leftData, rightData} = getData().main;
      let params = {
        cateId: selectId,
        goodsName: '',
        keywords: '',
        pageNum,
        pageSize: 16,
        sortFlag: 0,
      };
      let result = await api.pointsMallController.page(params); //查询积分商品列表
      if (result.pointsGoodsVOPage.content.length > 0) {
        let rows = result.pointsGoodsVOPage.content;
        let leftData = [],
          rightData = [];
        rows.map((item, index) => {
          if (index % 2 == 0) {
            leftData.push(item);
          } else {
            rightData.push(item);
          }
        });
        if (pageNum == 0) {
          action.commonChange('main.leftData', leftData);
          action.commonChange('main.rightData', rightData);
          action.commonChange('main.totalPages', result.pointsGoodsVOPage.totalPages);
        } else {
          let newLeftData = leftData.concat(leftData);
          let newRightData = rightData.concat(rightData);
          action.commonChange('main.leftData', newLeftData);
          action.commonChange('main.rightData', newRightData);
          action.commonChange('main.totalPages', result.pointsGoodsVOPage.totalPages);
        }
      }
    },
    /**
     * 签到
     */
    async sign() {
      let {main} = getData();
      let signFlag = main.signFlag;
      let successMessage = '恭喜您获得';
      if (!signFlag) {
        await api.customerSignRecordController.add('wechat'); //签到
        //触发任务，任务完成
        let task = Taro.getStorageSync('task');
        if (task) {
          task = JSON.parse(task);
          let id = task.id;
          const result = await api.TaskCenterController.completedTask({id});
          // setTimeout(()=>{
          Taro.showToast({
            title: `获得${task.taskInfoVO.rewardType == 0 ? task.taskInfoVO.rewardPoints : ''}${
              ['积分', '优惠券', '实物商品'][task.taskInfoVO.rewardType]
            }${task.taskInfoVO.rewardType == 2 ? '请到我的-我的奖励中填写收货地址' : ''}`,
            icon: 'none',
          });
          Taro.removeStorageSync('task');
          // },5000)
        }
        const res = await api.systemPointsConfigController.queryPointsConfig(); //查询积分设置-最新
        let continuousDays = main.continuousDays; //当前签到天数
        let giftType = res.giftType; //礼包类型 0：积分，1：优惠券，2：商品

        if (continuousDays == 6) {
          //已签到6天，再次签到可以获取礼包
          if (giftType == 0) {
            //积分
            successMessage = successMessage + res.giftValue + '积分';
          } else if (giftType == 1) {
            //优惠券
            successMessage = successMessage + res?.couponInfo?.couponName;
          } else {
            //商品
            successMessage = successMessage + res?.goodsInfo?.goodsInfoName;
          }

          action.commonChange([
            {paths: 'main.successMessage', value: successMessage},
            {paths: 'main.continuousDays', value: 7},
            {paths: 'main.giftType', value: giftType},
            {paths: 'main.showMode', value: res.status == 1 ? true : false}, //0未启用，1启用
          ]);
        } else {
          Taro.showToast({
            title: '签到成功',
            icon: 'none',
            duration: 3000,
          });
        }
        // 签到满7天获得
        // const pointsIncrease = res1.signPoint;
        // if (main.pointsFlag && main.growthFlag) {
        //   if (main.growthValue == 0 || main.growthValue == null) {
        //     successMessage = successMessage + pointsIncrease + '积分';
        //   } else if (main.signPoint == 0 || main.signPoint == null) {
        //     successMessage = successMessage  + main.growthValue + '成长值';
        //   } else {
        //     successMessage = successMessage  + pointsIncrease + '积分,' + main.growthValue + '成长值';
        //   }
        // } else if (main.pointsFlag && !main.growthFlag) {
        //   if (main.signPoint != 0 && main.signPoint != null) {
        //     successMessage = successMessage + pointsIncrease + '积分';
        //   }
        // } else if (!main.pointsFlag && main.growthFlag) {
        //   if (main.growthValue != 0 && main.growthValue != null) {
        //     successMessage = successMessage  + main.growthValue + '成长值';
        //   }
        // }

        // let days = main.daysNumArr;
        // let signDate = new Date(Date.now());
        // days.push(signDate.getDate());
        // main.userInfo.signContinuousDays = main.userInfo.signContinuousDays + 1;

        // action.commonChange([
        //   {paths: 'main.signFlag', value: !signFlag},
        //   {paths: 'main.isOpened', value: true},
        //   {paths: 'main.toastContent', value: successMessage},
        // ]);

        action.page();
      }
    },
  };
  return action;
};

function getData(): IAllReducerProps {
  return {
    main: getReducerData('packageCPointsMallMain'),
  };
}

//create by moon https://github.com/creasy2010/moon
